package com.danieltoms.gcSync.google.feed;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;

import javax.microedition.io.HttpConnection;

import net.rim.device.api.xml.parsers.DocumentBuilder;
import net.rim.device.api.xml.parsers.DocumentBuilderFactory;
import net.rim.device.api.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.danieltoms.gcSync.GcSyncStore;
import com.danieltoms.gcSync.google.GoogleContact;
import com.danieltoms.gcSync.google.GoogleLoginException;
import com.danieltoms.io.HttpConnectionHelper;

public class GoogleUpdateFeed
{

	private String _url = null;
	private static GoogleContact _contact;

	public GoogleUpdateFeed()
	{

	}

	static class PrepareRequest implements HttpConnectionHelper.Callback
	{

		private static final String APPLICATION_ATOM_XML = "application/atom+xml";
		private static final String CONTENT_TYPE = "Content-Type";
		private static final String EN_US = "en-US";
		private static final String ACCEPT_LANGUAGE = "Accept_Language";
		private static final String MIDP1 = "Profile/MIDP-1.0 Configuration/CLDC-1.0";
		private static final String USER_AGENT = "User-Agent";
		public static final Hashtable m_args = new Hashtable();

		public void prepareRequest(String originalURL, HttpConnection conn) throws IOException
		{

			conn.setRequestMethod(HttpConnection.POST);
			conn.setRequestProperty("X-HTTP-Method-Override", (String) m_args.get("action"));
			conn.setRequestProperty(USER_AGENT, MIDP1);
			conn.setRequestProperty(ACCEPT_LANGUAGE, EN_US);
			conn.setRequestProperty(CONTENT_TYPE, APPLICATION_ATOM_XML);
			conn.setRequestProperty("Authorization", "GoogleLogin auth=" + m_args.get("auth"));

		}

		public void preparePost(HttpConnection c) throws IOException
		{
			if (((String) m_args.get("action")).equals("PUT"))
			{
				_contact.printXML(System.out);
				DataOutputStream os = c.openDataOutputStream();
				os.write("<?xml version=\"1.0\"?>\n".getBytes());
				_contact.printXML(os);
				os.flush();
			}
		}

	}

	private PrepareRequest _prepareRequest = new PrepareRequest();

	protected InputStream getFeedInputStream() throws GoogleLoginException, IOException
	{

		HttpConnection c = null;
		InputStream is = null;

		int rc = -1;

		_prepareRequest.m_args.put("auth", GcSyncStore.instance().getAuthToken());

		c = HttpConnectionHelper.connect(_url, _prepareRequest);

		rc = c.getResponseCode();
		System.out.println("updateContact return code: " + rc);

		if (rc == HttpConnection.HTTP_UNAUTHORIZED)
		{
			// our auth token expired, login again and try a new one

			GoogleClientLoginFeed gcl = new GoogleClientLoginFeed();
			if (gcl.authenticate(GcSyncStore.instance().getEmail(), GcSyncStore.instance().getPassword()))
			{
				// try again
				_prepareRequest.m_args.put("auth", GcSyncStore.instance().getAuthToken());

				c = HttpConnectionHelper.connect(_url, _prepareRequest);

				rc = c.getResponseCode();
				System.out.println("getFeedInputStream return code: " + rc);
				// if we fail again, our password must have changed
			}
		}

		is = c.openDataInputStream();

		return is;

	}

	public void log(String log)
	{
		System.out.println(log);
	}

	public GoogleContact updateContact(GoogleContact gc) throws ParserConfigurationException, SAXException
	{
		_contact = gc;
		_url = gc.getEditURL();
		PrepareRequest.m_args.put("action", "PUT");
		GoogleContact ret = null;
		try
		{
			Document document = null;

			NodeList nl = null;

			InputStream is = getFeedInputStream();

			// Build a document based on the XML file.
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();

			document = builder.parse(is);

			nl = document.getElementsByTagName("entry");

			int length = nl.getLength();

			System.out.println("Number of entries: " + length);

			Element n = (Element) nl.item(0);

			// add these namespaces so we can update later.
			n.setAttribute("xmlns", "http://www.w3.org/2005/Atom");
			n.setAttribute("xmlns:gContact", "http://schemas.google.com/contact/2008");
			n.setAttribute("xmlns:gd", "http://schemas.google.com/g/2005");
			ret = new GoogleContact(n);
		}
		catch (GoogleLoginException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return ret;
	}

	public void deleteContact(GoogleContact gc) throws ParserConfigurationException, SAXException
	{
		_contact = gc;
		_url = gc.getEditURL();
		PrepareRequest.m_args.put("action", "DELETE");
		GoogleContact ret = null;
		try
		{
			Document document = null;

			NodeList nl = null;

			getFeedInputStream();

		}
		catch (GoogleLoginException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
